package cj.web.rss.controllers;

import java.util.EnumSet;
import java.util.List;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.DateUtils;
import cj.web.rss.constants.EvacuateEnum;
import cj.web.rss.constants.MemuEnum;
import cj.web.rss.dao.RssNewsDAO;
import cj.web.rss.domain.RssNews;
import cj.web.rss.util.LzstoneQuartzTask;
import cj.web.rss.util.RssUtil;

@Path("/rssNews")
public class RssNewsController{

	private static Logger logger = Logger.getLogger(RssNewsController.class.getName());
	
	@Autowired
	private RssNewsDAO rssNewsDao;
	
	@Get("show")
	public String show(Model model,RssNews rssNews) {
		//MemuEnum
        model.add("MemuEnum",MemuEnum.rssnews);
        model.add("evacuateEnum",EnumSet.allOf(EvacuateEnum.class));
		return "/views/news/newsList.vm";
	}

	@Post("getList")
	public String queryList(RssNews rssNews) {
	
		JSONObject jo = new JSONObject();
		
		List<RssNews> rssNewslis = rssNewsDao.query(rssNews);
		for(RssNews obj:rssNewslis)
		{
			obj.setPubDate(DateUtils.getMinusTime(obj.getPubDate(), DateUtils.DATE_FULL_STR, 0));
			obj.setUpdateDate(DateUtils.getMinusTime(obj.getUpdateDate(), DateUtils.DATE_FULL_STR, 0));
		}
		int size = rssNewsDao.querysize(rssNews);
		jo.put("data", rssNewslis);
		jo.put("draw", rssNews.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@"+jo.toString();
	}
	
	@Get("view")
	public String view(Model model,@Param("id") int id)
	{
		//详情
		RssNews obj = rssNewsDao.queryById(id);
		//MemuEnum
        model.add("MemuEnum",MemuEnum.rssnews);
        model.add("obj", obj);
        return "/views/news/newsDetail.vm";
	}
	
	@Get("rssRecord")
	public String rssRecord(Model model)
	{
        model.add("MemuEnum",MemuEnum.rssrecord);
        return "/views/news/rssRecord.vm";
	}
	
	@Get("refresh")
	public String refresh()
	{
		String responseRss = RssUtil.invokeRss();
		
		List<RssNews> rssNewslis = RssUtil.analysisRssItem(responseRss);
		
		for(RssNews obj:rssNewslis)
		{
			String link = obj.getLink();//链接地址唯一值
			String updateDate = obj.getUpdateDate();//最后更新时间
			
			//正常
			try {
				int rssNewsSize = rssNewsDao.queryByLinkSize(link,updateDate);
				
				if(rssNewsSize==0)
				{
					rssNewsDao.create(obj);
				}
				
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
			
		return "r:show";
	}
}
